module.exports = function(window, document) {
	var apivm = require('../../common/avm.min')(window, document);
	var avm = apivm;
	var api = apivm.api;
	var Component = apivm.Component;
	var $ = apivm.$;
	(function() {
	/*
	 * APICloud JavaScript Library
	 * Copyright (c) 2014 apicloud.com
	 */
	var $kn = {
		byId: function byId(id) {
			return document.getElementById(id);
		},
		ajax: function ajax(p, callback) {
			var _this = this;
			var param = p;
			if (!param.headers) {
				param.headers = {};
			}
			param.headers["x-apicloud-mcm-key"] = "cZKzX7DabDmYyfez";
			if (param.data && param.data.body) {
				param.headers["Content-Type"] = "application/json; charset=utf-8";
			}
			if (param.url) {
				var baseUrl = "https://a8888888888888-pd.apicloud-saas.com/api/";
				param.url = baseUrl + param.url;
			}
			api.ajax(param, function(ret, err) {
				if (callback) callback(ret, err);
				if (ret) {
					var status = ret.status;
					if (status && status == 4001) {
						var didShowLogoutAlert = api.getGlobalData({
							key: "didShowLogoutAlert"
						});

						if (!didShowLogoutAlert) {
							api.setGlobalData({
								key: "didShowLogoutAlert",
								value: true
							});

							_this.setUserInfo("");
							api.alert(
								{
									msg: "登录已失效，请重新登录"
								},
								function() {
									api.setGlobalData({
										key: "didShowLogoutAlert",
										value: false
									});

									api.closeToWin({
										name: "root"
									});
								}
							);
						}
					}
				}
			});
		},
		getUserInfo: function getUserInfo() {
			var value = api.getPrefs({
				key: "userInfo",
				sync: true
			});

			return value ? JSON.parse(value) : "";
		},
		setUserInfo: function setUserInfo(userInfo) {
			api.setPrefs({
				key: "userInfo",
				value: userInfo
			});
		},
		getCurrentCityInfo: function getCurrentCityInfo() {
			var value = api.getPrefs({
				key: "currentCity",
				sync: true
			});

			return value ? JSON.parse(value) : "";
		},
		setCurrentCityInfo: function setCurrentCityInfo(cityInfo) {
			api.setPrefs({
				key: "currentCity",
				value: cityInfo
			});
		},
		getWareTypeList: function getWareTypeList() {
			var value = api.readFile({
				sync: true,
				path: "fs://WareTypeList"
			});

			return value ? JSON.parse(value) : "";
		},
		setWareTypeList: function setWareTypeList(list) {
			api.writeFile({
				path: "fs://WareTypeList",
				data: JSON.stringify(list)
			});
		},
		fitRichText: function fitRichText(richtext, width) {
			var str = '<img style="max-width:' + width + 'px;"';
			var result = richtext.replace(/\<img/gi, str);
			return result;
		}
	};

	var MainFrame = /*@__PURE__*/ (function(Component) {
		function MainFrame(props) {
			Component.call(this, props);
			this.data = {
				bannerUrl: "",
				skip: 0,
				LIMIT: 10,
				haveMoreData: true,
				refreshState: "normal"
			};
			this.compute = {
				refreshIconClass: function() {
					if (this.data.refreshState == "normal") {
						return "refreshIcon-normal";
					} else if (this.data.refreshState == "dragging") {
						return "refreshIcon-dragging";
					} else if (this.data.refreshState == "refreshing") {
						return "refreshIcon-refreshing";
					}
				},
				refreshLoadingClass: function() {
					if (this.data.refreshState == "refreshing") {
						return "refreshLoading-refreshing";
					} else {
						return "refreshLoading";
					}
				},
				refreshStateDesc: function() {
					if (this.data.refreshState == "normal") {
						return "下拉可以刷新";
					} else if (this.data.refreshState == "dragging") {
						return "松开可以刷新";
					} else if (this.data.refreshState == "refreshing") {
						return "刷新中...";
					}
				}
			};
		}

		if (Component) MainFrame.__proto__ = Component;
		MainFrame.prototype = Object.create(Component && Component.prototype);
		MainFrame.prototype.constructor = MainFrame;
		MainFrame.prototype.onstatechange = function(e) {
			var state = e.detail.state;
			if (state == "normal") {
				this.data.refreshState = "normal";
			} else if (state == "dragging") {
				this.data.refreshState = "dragging";
			} else if (state == "refreshing") {
				this.data.refreshState = "refreshing";
				this.fnGetWareList(false);
			}
		};
		MainFrame.prototype.apiready = function() {
			this.data.bannerUrl = api.pageParam.wareType.banner.url;

			var that = this;
			setTimeout(function() {
				that.data.refreshState = "refreshing";
				that.fnGetWareList(false);
			}, 200);

			var that = this;
			// 监听onGetCartInfo事件（自定义），更新商品数量和总金额
			api.addEventListener(
				{
					name: "onGetCartInfo"
				},
				function(ret, err) {
					if (that.dataList && that.dataList.length > 0) {
						that.getFixedWareList(that.dataList, ret.value.wareList);
						var listView = document.getElementById("listView");
						listView.load({
							data: that.dataList
						});
					}
				}
			);
		};
		MainFrame.prototype.fnGetWareList = function(loadMore_) {
			// 如果是加载更多，需要实现分页
			if (loadMore_) {
				this.data.skip += this.data.LIMIT;
			} else {
				this.data.skip = 0;
			}

			var currentCity = $kn.getCurrentCityInfo();
			var that = this;
			// 根据城市和商品分类获得相应的商品列表
			$kn.ajax(
				{
					url: "wares/getWareList",
					method: "post",
					data: {
						body: {
							supportAreaId: currentCity ? currentCity.id : "",
							wareTypeId: api.pageParam.wareType.id,
							skip: this.data.skip,
							limit: this.data.LIMIT
						}
					}
				},

				function(ret, err) {
					if (ret && ret.data) {
						var cartData = api.getGlobalData({key: "cartInfo"});
						var data = ret.data;
						that.getFixedWareList(data, cartData ? cartData.wareList : null);
						var listView = document.getElementById("listView");
						if (loadMore_) {
							listView.insert({
								data: data
							});

							that.dataList = that.dataList.concat(data);
						} else {
							that.dataList = data;
							listView.load({
								data: data
							});
						}
						that.data.haveMoreData = data.length == that.data.LIMIT;
					} else {
						api.toast({
							msg: "加载数据失败",
							duration: 2000,
							location: "bottom"
						});
					}
					that.data.refreshState = "normal";
				}
			);
		};
		MainFrame.prototype.getFixedWareList = function(wareList, cartWareList) {
			for (var i = 0; i < wareList.length; i++) {
				var item = wareList[i];
				item.wareCount = 0;
				if (cartWareList && cartWareList.length > 0) {
					for (var j = 0; j < cartWareList.length; j++) {
						var cartItem = cartWareList[j];
						if (cartItem.id == item.id) {
							item.wareCount = cartItem.wareCount;
						}
					}
				}
			}
		};
		MainFrame.prototype.onscrolltolower = function() {
			if (this.data.haveMoreData) {
				this.fnGetWareList(true);
			}
		};
		MainFrame.prototype.fnOpenDetailWin = function(e) {
			var id = e.currentTarget.dataset.id;
			var wareCount = e.currentTarget.dataset.wareCount;
			api.openWin({
				name: "ware" + id,
				url: "../ware/ware.stml",
				pageParam: {
					wareId: id,
					wareCount: wareCount
				},

				animation: {
					type: "fade"
				}
			});
		};
		MainFrame.prototype.fnMinus = function(e) {
			if (!$kn.getUserInfo()) {
				api.openWin({
					name: "login",
					url: "../login/login.stml"
				});

				return;
			}
			var index = e.currentTarget.dataset.index;
			var item = this.dataList[index];
			if (item.wareCount > 0) {
				item.wareCount--;
				var listView = document.getElementById("listView");
				listView.update({
					index: index,
					item: item
				});

				// 发送购物车更新自定义事件，传递商品Id和商品数量
				api.sendEvent({
					name: "updateShoppingCart",
					extra: {
						wareId: item.id,
						wareCount: item.wareCount
					}
				});
			}
		};
		MainFrame.prototype.fnAdd = function(e) {
			if (!$kn.getUserInfo()) {
				api.openWin({
					name: "login",
					url: "../login/login.stml"
				});

				return;
			}
			var index = e.currentTarget.dataset.index;
			var item = this.dataList[index];
			item.wareCount++;
			var listView = document.getElementById("listView");
			listView.update({
				index: index,
				item: item
			});

			// 发送购物车更新自定义事件，传递商品Id和商品数量
			api.sendEvent({
				name: "updateShoppingCart",
				extra: {
					wareId: item.id,
					wareCount: item.wareCount
				}
			});
		};
		MainFrame.prototype.render = function() {
			var this$1 = this;
			return apivm.h(
				"list-view",
				{
					id: "listView",
					class: "main",
					onscrolltolower: this.onscrolltolower,
					$bindCell_: function(celltype, item, index) {
						return apivm.h(
							"cell",
							{class: "cell"},
							apivm.h(
								"view",
								{
									"data-id": item.id,
									"data-wareCount": item.wareCount,
									class: "container",
									onclick: this$1.fnOpenDetailWin
								},
								apivm.h("image", {
									class: "thumbnail",
									src: item.thumbnail,
									placeholder: "../../image/default_square.png"
								}),
								apivm.h(
									"view",
									{class: "info"},
									apivm.h(
										"text",
										{class: "info-name"},
										item.name + " " + (item.unit || "")
									),
									apivm.h("text", {class: "info-description"}, item.description),
									apivm.h("text", {class: "info-price"}, "￥" + item.price),
									apivm.h("text", {class: "info-origin-price"}, "￥" + item.originPrice)
								),
								apivm.h(
									"view",
									{class: "control"},
									apivm.h("image", {
										class: "minus" + (item.wareCount > 0 ? "" : " none"),
										"data-index": index,
										src: "../../image/minus.png",
										onclick: this$1.fnMinus
									}),
									apivm.h(
										"text",
										{class: "count" + (item.wareCount > 0 ? "" : " none")},
										item.wareCount
									),
									apivm.h("image", {
										class: "add",
										"data-index": index,
										src: "../../image/add.png",
										onclick: this$1.fnAdd
									})
								)
							)
						);
					}
				},
				apivm.h(
					"refresh",
					{
						class: "refresh",
						state: this.data.refreshState,
						onstatechange: this.onstatechange
					},
					apivm.h("image", {
						class: this.refreshIconClass,
						src: "../../image/refresh.png"
					}),
					apivm.h("image", {
						class: this.refreshLoadingClass,
						src: "../../image/loading.gif"
					}),
					apivm.h("text", {class: "refreshStateDesc"}, this.refreshStateDesc)
				),
				apivm.h(
					"list-header",
					{class: "header"},
					apivm.h("image", {
						class: "banner",
						src: this.data.bannerUrl,
						placeholder: "../../image/default_rect.png",
						thumbnail: "false",
						mode: "widthFix"
					})
				),

				apivm.h(
					"list-footer",
					{class: "footer"},
					apivm.h(
						"text",
						{class: "loadDesc"},
						this.data.haveMoreData ? "加载中..." : "没有啦！"
					)
				)
			);
		};

		return MainFrame;
	})(Component);
	apivm.define("main_frame", MainFrame);
	apivm.render(apivm.h("main_frame", null), "body");
})();

	window['createApp'] = function() {
		apivm.$_start();
	}
	return avm;
}